import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/LayOut'
import { isLogin } from '@/utils'

const routes = [
  {
    path: '/',
    name: '首页',
    meta: {
      roles: '*'
    },
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        name: '图表',
        meta: {
          roles: '*'
        },
        component: () => import('@/views/DashBoard')
      },
      {
        path: '/itemList',
        name: '商品列表',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/ItemList')
      },
      {
        path: '/itemAdd',
        name: '增加商品',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/ItemList/ItemAdd')
      },
      {
        path: '/itemUpdate',
        name: '修改商品',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/ItemList/ItemUpdate')
      },
      {
        path: '/cateList',
        name: '商品分类',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/CateList')
      },
      {
        path: '/userInfo',
        name: '个人中心',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/UserInfo')
      }
    ],
    component: Layout
  },
  {
    path: '/login',
    name: '登录',
    meta: {
      roles: ['admin', 'a', 'b']
    },
    component: () => import('@/views/LoginPage')
  },
  {
    path: '/setting',
    name: '设置',
    meta: {
      roles: ['a', 'b']
    },
    component: () => import('@/views/SettingPage')
  },
  {
    path: '/noauth',
    name: '权限',
    meta: {
      roles: '*'
    },
    component: () => import('@/views/NoPermission')
  },
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/views/NotFound')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// // 路由鉴权
// router.beforeEach((to, form, next) => {
//   const passRouter = ['/login']
//   if (passRouter.includes(to.path)) {
//     next()
//   } else {
//     // 非登录页 鉴权
//     if (isLogin()) {
//       next()
//     } else {
//       next('/login')
//     }
//   }
// })

// 添加前置守卫 判断 是否登录
router.beforeEach((to) => {
  // 判断是否登录
  if (to.path !== '/login') {
    if (!isLogin()) {
      return '/login'
    } else {
      // 已经登录 判断当前用户能否访问该路由
      const role = localStorage.getItem('role')
      if (to.meta.roles === '*' || to.meta.roles.includes(role)) {
        // 可以访问
        return true
      } else {
        return '/noauth'
      }
    }
  }
})
export default router
